import { clear_object, loc, obj_str, uDb, is_empty, cline } from 'sui';
import { code_value } from './ctl';

const reload = (hDone, cur, setMain) => {
    uDb(hDone, "code/get",
        {
            line: cline(),
            k: obj_str(cur, "sn"),
        },
        data => {
            if (is_empty(data)) {
                setMain(null);
                return;
            }

            const v = data.v;
            if (!v) {
                setMain(null);
                return;
            }

            v.forEach((d, i) => {
                code_value(d);
                d["index"] = i + 1;
            });
            setMain(v);
        }, e => setMain(null));
};

const update = (umd, cur, data, setMain) => {
    umd.startWait();

    uDb(null, "code/mditem",
        {
            line: cline(),
            v: {
                sn: obj_str(cur, "sn"),
                v: clear_object(data),
            }
        },
        r => reload(umd.endWait, cur, setMain),
        e => umd.setErr(loc("l_232")), true);
};

export {reload, update};
